﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using CNRegex.Web.Models;
using CNRegex.Entity;
using CNRegex.Biz.BizAccess;
using CNRegex.Web.Base;
using CNRegex.Biz;

namespace CNRegex.Web.Controllers
{
	public class AccountController : BaseController
	{
		private BizRegexUser bizRegexUser;
		private BizRegexUserStateInfo bizRegexStateInfo;
		public AccountController()
		{

		}

		public ActionResult Register()
		{
			ViewBag.Title = "用户注册";
			ViewBag.RegisterZone = "display:block;";
			ViewBag.LoginZone = "display:none;";
			return View();
		}

		[HttpPost]
		public ActionResult Register(RegexUser model)
		{
			model.RegisterDate = DateTime.Now;
			bizRegexUser.Save(model);

			return Login(model.Name, model.Password);
		}

		[HttpPost]
		public ActionResult IsNameExist(string name)
		{
			return bizRegexUser.Get(name) == null ? Content(false.ToString()) : Content(true.ToString());
		}


		public ActionResult Login()
		{
			if (FrontContext.CurrentRegexUser!=null)
				return Redirect(string.Format("/{0}", FrontContext.CurrentRegexUser.Name));
			ViewBag.Title = "用户登录";
			ViewBag.RegisterZone = "display:none;";
			ViewBag.LoginZone = "display:block;";
			ViewBag.ShowLoginInfo = TempData["TipInfo"] == null ? "inline" : "none";
			ViewBag.ShowErrorLogin = TempData["TipInfo"] == null ? "none" : "inline";
			return View("Register");
		}

		[HttpPost]
		public ActionResult Login(string name,string password)
		{
			RegexUser user = bizRegexUser.Get(name, password);
			if (user == null)
			{
				TempData["TipInfo"] = true;
				return RedirectToAction("Login");
			}
			FrontContext.CurrentRegexUser = user;
			//update user state information
			bizRegexStateInfo.UpdateUserState(user,Request.UserHostAddress);
			return Redirect(string.Format("/{0}",name));
		}

		public ActionResult LoginOut()
		{
			FrontContext.CurrentRegexUser = null;
			return Redirect("/");
		}

		public ActionResult Test()
		{
			return View(bizRegexUser.List());
		}

	}
}
